﻿using System;
using System.Runtime.Caching;
using System.Web.Caching;
using System.Web;
using System.Collections;

namespace Raffles.OA.Utility
{
    /// <summary>
    /// 缓存类,此类型是线程安全的
    /// </summary>
    public class CacheHelper
    {
        private static Cache cache = HttpRuntime.Cache;

        /// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public static object GetCache(string cacheKey)
        {
            var obj = cache.Get(cacheKey);
            return obj;
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="obj"></param> 
        public static void SetCache(string cacheKey, object obj)
        {
            cache.Insert(cacheKey, obj, null, DateTime.MaxValue, TimeSpan.Zero);
        }

        /// <summary>
        /// 移除指定缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        public static void RemoveCache(string cacheKey)
        {
            cache.Remove(cacheKey);
        }

        /// <summary>
		/// 移除全部缓存
		/// </summary>
		public static void RemoveCache()
        {
            IDictionaryEnumerator enumerator = cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                cache.Remove(enumerator.Key.ToString());
            }
        }

        /// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public static T GetCache<T>(string cacheKey) where T : class
        {
            if (cache[cacheKey] != null)
            {
                return (T)cache[cacheKey];
            }
            return default(T);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="cacheKey"></param>
        public static void SetCache<T>(T value, string cacheKey) where T : class
        {
            cache.Insert(cacheKey, value, null, DateTime.MaxValue, TimeSpan.Zero);
        }
    }
}